<template>
	<section class="mc-user-dialog">
		<el-dialog title="添加成员" width="650px" :visible="DialogVisible" :before-close="change" append-to-body>
			<div class="">
				<div class="el-transfer">
					<div class="el-transfer-panel" titles="" style="width:200px;" buttontexts="" filterplaceholder="请输入" leftdefaultchecked="" rightdefaultchecked="" value="">
						<p class="el-transfer-panel__header">待选成员</p>
						<div class="el-transfer-panel__body" style="height: auto;padding-bottom: 2px;">
							<el-input placeholder="请输入关键字" size="small" icon="circle-close" v-model="searchkey" @change="onSearch" :on-icon-click="onClearSearch">
							</el-input>
							<div v-show="searchkey" class="user-transfer" v-loading="loading">
								<el-checkbox-group class="el-transfer-panel__list" style="height: 370px;" v-model="waitingCheckList">
									<el-checkbox v-for="item in waitingUserList" :label="item.id" :key="item.id" v-if="item.display"><i class="iconfont icon-employee" style="color:#1d8ce0;"></i>{{item.name}}</el-checkbox>
								</el-checkbox-group>
							</div>
							<div v-show="!searchkey">
								<div style="height: 370px;overflow: auto;">
									<el-tree ref="userDialogTree" :data="orgData" :props="orgProps" :load="loadOrg" lazy show-checkbox :render-content="renderContent"></el-tree>
								</div>
							</div>

						</div>

					</div>
					<div class="el-transfer__buttons">
						<el-button :plain="true" type="primary" @click="onLeft"><i class="el-icon-arrow-left"></i></el-button>
						<el-button :plain="true" type="primary" @click="onRight"><i class="el-icon-arrow-right"></i></el-button>
					</div>
					<div class="el-transfer-panel" titles="" style="width:200px;" buttontexts="" leftdefaultchecked="" rightdefaultchecked="" value="">
						<p class="el-transfer-panel__header">已选审批人</p>
						<div class="el-transfer-panel__body" style="height: auto;padding-bottom: 2px;">
							<div class="user-transfer">
								<el-checkbox-group class="el-checkbox-group el-transfer-panel__list" style="height: 400px;" v-model="selectedCheckList">
									<el-checkbox v-for="item in selectedUserList" :key="item.id" :label="item.id">{{item.name}}</el-checkbox>
								</el-checkbox-group>
							</div>
						</div>

					</div>
				</div>
			</div>
			<div slot="footer" class="dialog-footer">
				<el-button type="primary" @click="onSubmit">确 定</el-button>

			</div>
		</el-dialog>
	</section>
</template>
<script>
  import {AjaxByAll} from '@/api/api'
	export default {
		data() {
			return {
				myDialogVisible: this.DialogVisible,
				onSubmitData:false,
				loading: false,
				selectedCheckList: [],
				selectedUserList: [],
                orgType:null,
				waitingCheckList: [],
				waitingUserList: [],
				searchkey: null,
				timeoutHandle: null,
				orgData: [],
				orgDataCheck: null,
				orgProps: {
					label: 'label',
					children: 'children'
				},

			}
		},
		methods: {
			getCheckedNodes() {
				return this.$refs.userDialogTree.getCheckedNodes();
			},
			renderContent(h, {
				node,
				data,
				store
			}) {
				if(data.data.isUser) {
					return(
						<span>
					<span>
					<span style="font-size:12px;">
					<i class="iconfont icon-employee" style="color:#1d8ce0;"></i>
					{node.label}</span>
					</span>
					<span style="float: right; margin-right: 20px">
					</span>
					</span>);
				} else {
					return(
						<span>
					<span>
					<span style="font-size:12px;">
					<i class="iconfont icon-e66f"></i>
					{node.label}</span>
					</span>
					<span style="float: right; margin-right: 20px">
					</span>
					</span>);
				}

			},
			onLeft() {
				var selecteduser = [];
//				console.log('left')
				for(var i = 0; i < this.selectedUserList.length; i++) {
					var exist = false;
					for(var j = 0; j < this.selectedCheckList.length; j++) {
						if(this.selectedUserList[i].id === this.selectedCheckList[j]) {
							exist = true;
						}
					}
					if(!exist) {
						selecteduser.push(this.selectedUserList[i]);
					}
				}
				for(var m = 0; m < this.waitingUserList.length; m++) {
					for(var n = 0; n < this.selectedCheckList.length; n++) {
						if(this.waitingUserList[m].id === this.selectedCheckList[n]) {
							this.waitingUserList[m].display = true;
						}
					}
				}
				this.selectedCheckList = [];
				this.selectedUserList = selecteduser;
			},
			onRight() {
				if(this.searchkey) {
					/*==============从查询列表选择用户==========*/
					/*等待添加的用户数组*/
					var selecteduser = [];
					for(var i = 0; i < this.waitingCheckList.length; i++) {
						/*用户object*/
						var user = null;
						//根据checkbox返回的ID查找用户object
						for(var j = 0; j < this.waitingUserList.length; j++) {
							if(this.waitingCheckList[i] === this.waitingUserList[j].id) {
								user = this.waitingUserList[j];
							}
						}
						/*判断选择的用户数组是否已经存在该用户对象*/
						var exist = false;
						for(var k = 0; k < this.selectedUserList.length; k++) {
//						    console.log(user,this.selectedUserList[k]);
							if(user.id === this.selectedUserList[k].id) {
								exist = true;
							}
						}
						/*如果如果不在已选的数组中就添加*/
						if(!exist) {
							selecteduser.push(user);
						}
					}
					/*往已选的数组中添加新数据*/
					if(this.only){
					    if(selecteduser.length > 0){
                            this.selectedUserList = [ selecteduser[selecteduser.length - 1] ];
						}
					}else{
                        for(var l = 0; l < selecteduser.length; l++) {
                            this.selectedUserList.push(selecteduser[l]);
                        }
					}
					/*将已选择的数据隐藏*/
					for(var m = 0; m < this.waitingUserList.length; m++) {
						for(var n = 0; n < this.selectedUserList.length; n++) {
							if(this.waitingUserList[m].id === this.selectedUserList[n].id) {
								this.waitingUserList[m].display = false;
							}
						}
					}
					/*已选择的待选数据清空*/
					this.waitingCheckList = [];
				} else {
					/*==============从组织机构选择用户==========*/
					var checkNodes = this.getCheckedNodes();
					/*等待添加到已选组的用户*/
					var selecteduser = [];
					/*校验数据，并添加到已选组数组*/
//					console.log(checkNodes)
					for(var i = 0; i < checkNodes.length; i++) {
						if(checkNodes[i].data) {
							var exist = false;
							/*判断选择的用户数组是否已经存在该用户对像*/
							for(var k = 0; k < this.selectedUserList.length; k++) {
//							    console.log(checkNodes[i]);
								/*if(checkNodes[i].data.userId === this.selectedUserList[k].id) {
									exist = true;
								}*/
                                if(checkNodes[i].data.id === this.selectedUserList[k].id) {
                                    exist = true;
                                }
							}
							/*如果如果不在已选的数组中就添加*/
							if(!exist&&((this.orgType&checkNodes[i].data.orgType)==checkNodes[i].data.orgType)) {
								/*selecteduser.push({
									id: checkNodes[i].data.userId,
									name: checkNodes[i].data.userFullName
								});*/
                                selecteduser.push({
                                    id: checkNodes[i].data.id,
                                    name: checkNodes[i].data.name,
                                    orgType: checkNodes[i].data.orgType
                                });
							}
						}
					}


					/*往已选的数组中添加新数据*/
					if(this.only){

					    if(selecteduser.length > 0){
                            this.selectedUserList = [ selecteduser[selecteduser.length - 1] ];
                          //  console.log(this.selectedUserList);
                           // alert(this.selectedUserList.length+'ss')
						}
					}else{

                        for(let l = 0; l < selecteduser.length; l++) {

                            this.selectedUserList.push(selecteduser[l]);
                        }
                        console.log(this.selectedUserList);

					}
				}
			},
			AddSelectedUser(event) {
				console.log(event);
			},
			onClearSearch() {
				this.searchkey = '';
			},
			onSearch() {
				var self = this;
				if(self.timeoutHandle) {
					clearTimeout(self.timeoutHandle);
				}
				self.loading = true;
				self.waitingUserList = [];
				self.timeoutHandle = setTimeout(function() {
					if(self.searchkey) {
                        var formdata= {
                            searchKey: self.searchkey,
                            pageSize: 20,
							orgType: self.orgType
                        }
                        AjaxByAll('post', 'sys/org/address/search', formdata).then(data => {
							self.loading = false;
							if(data.code === 200) {
								var results = data.data;
								var users = [];
								for(var i = 0; i < results.length; i++) {
									/*var user = {
									 id: results[i].userId,
									 name: results[i].userFullName,
									 display: true
									 };*/
                                    var user = {
                                        id: results[i].id,
                                        name: results[i].name,
										orgType:results[i].orgType,
                                        display: true
                                    };
									for(var j = 0; j < self.selectedUserList.length; j++) {
										if(results[i].id === self.selectedUserList[j].id) {
											user.display = false;
										}
									}
									users.push(user);
								}
								self.waitingUserList = users;
							}
						});
					}
				}, 500);
			},
			loadOrg(node, resolve) {
				if(node.data && node.data.data && node.data.data.isUser) {
					return resolve([]);
				}
                var urls = 'sys/org/address/tree';
				 var id=null;
				if(node.data && node.data.id) {
					id= node.data.id;

				}
                var formData = {id: id,orgType:this.orgType};
				var subNodes = [];

                AjaxByAll('post', urls, formData).then(data => {

					if(data.code === 200) {
						for(var i = 0; i < data.data.length; i++) {
							subNodes.push({
								children: [],
								label: data.data[i].name,
								id: data.data[i].id,
                                orgType:data.data[i].orgType,
								data: data.data[i],
							});
						}
					}

						return resolve(subNodes);

				});
				　
			},
            //深度克隆对象，数组
            clone(obj){
                if(!(typeof obj === 'object' && (Object.prototype.toString.call(obj) === "[object Object]" || Object.prototype.toString.call(obj) === "[object Array]"))){
                    return 'This is not an array or an object'
                }else{
                    var newObj = (Object.prototype.toString.call(obj) === "[object Object]") ? {} : [];
                    for(var item in obj){
                        if(obj.hasOwnProperty(item)){
                            if(typeof obj[item] === 'object' && (Object.prototype.toString.call(obj[item]) === "[object Object]" || Object.prototype.toString.call(obj[item]) === "[object Array]") ){
                                newObj[item] = this.clone(obj[item]);
                            }else{
                                newObj[item] = obj[item];
                            }
                        }
                    }
                    return newObj;
                }
            },
			//关闭
			change() {
				this.myDialogVisible = false;

				//
                this.$emit("on-dialog-change", {
                    users: this.params.user,
                     onSubmitData:false,
                    visible: this.myDialogVisible
                 });
			},
			//确认
			onSubmit() {
				this.myDialogVisible = !this.myDialogVisible;
                console.log(this.selectedUserList);

                this.$emit("on-dialog-change", {
                    users: this.selectedUserList,
                    onSubmitData:true,
                    visible: this.myDialogVisible
                });
			}
		},
		watch: {
			DialogVisible(val) {
				this.myDialogVisible = val;
			},
			/*myDialogVisible(val) {
				this.$emit("on-dialog-change", {
					users: this.selectedUserList,
					visible: val
				});
			},*/
			'params.user': {　　　　
				handler(newValue, oldValue) {
//					console.log(newValue,'{{}}');
					if(newValue) {
						//this.selectedUserList = this.clone(newValue);
					}
				},
				deep: true　　
			},
            'params.orgType': {
                handler(newValue, oldValue) {
//					　
                    if(newValue) {
                      //  this.orgType = newValue;
                    }
                },
                deep: true
            }
		},
		mounted: function() {

		    if(this.params.user.length>0) {
                this.selectedUserList =this.params.user;
            } else {
                this.selectedUserList = []
            }
		    this.orgType=this.params.orgType;
		},
		props: ['DialogVisible', 'params','only'],

	}
</script>

<style>

	.el-checkbox+.el-checkbox{
		margin-left: 0;
	}

	.user-transfer {
		/*text-align: center;*/
	}

	.user-transfer .el-transfer-panel__list {
		margin: 0;

		list-style: none;
		overflow: auto;
		box-sizing: border-box;
	}

	.user-transfer .el-checkbox {
		text-align: left;
		height: 32px;
		line-height: 32px;
		padding-left: 20px;
		display: block;
	}

	.user-transfer .el-checkbox:hover {
		background: #e4e8f1;
	}

	.mc-user-dialog .el-dialog {
		width: 650px;
	}

</style>
